<template>
  <a-modal
    :title="title"
    :width="700"
    :ok="false"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :okButtonProps="{ props: { disabled: disableSubmit } }"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <!-- 添加子架构 -->
    <div v-if="modelType == 3">
      <a-form :form="form"
        ><a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="子架构名称">
          <!-- <a-input placeholder="请输入子架构名称" v-decorator="['departName']" /> -->
          <a-input placeholder="请输入子架构名称" v-decorator="['departName', validatorRules.departName]" />
        </a-form-item>
      </a-form>
    </div>
    <!-- 添加同级架构 -->
    <div v-if="modelType == 4">
      <a-form :form="form"
        ><a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="同级架构名称">
          <a-input placeholder="请输入同级架构名称" v-decorator="['departName', validatorRules.departName]" />
        </a-form-item>
      </a-form>
    </div>
    <!-- 添加用户 -->
    <div v-if="modelType == 5 || modelType == 6">
      <a-transfer
        :data-source="mockData"
        :target-keys="targetKeys"
        :disabled="disabled"
        :show-search="showSearch"
        :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
        :show-select-all="false"
        @change="onChange"
      >
        <template
          slot="children"
          slot-scope="{
            props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
            on: { itemSelectAll, itemSelect },
          }"
        >
          <a-table
            :pagination="
              direction === 'left'
                ? pagination1
                : {
                    showTotal: (total, range) => {
                      return range[0] + '-' + range[1] + '共' + total + '条'
                    },
                  }
            "
            :row-selection="getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })"
            :columns="direction === 'left' ? leftColumns : rightColumns"
            :data-source="filteredItems"
            size="small"
            :style="{ pointerEvents: listDisabled ? 'none' : null }"
            :custom-row="
              ({ key, disabled: itemDisabled }) => ({
                on: {
                  click: () => {
                    if (itemDisabled || listDisabled) return
                    itemSelect(key, !selectedKeys.includes(key))
                  },
                },
              })
            "
            @change="onChange1"
          />
        </template>
      </a-transfer>
      <a-switch
        un-checked-children="显示搜索框"
        checked-children="显示搜索框"
        :checked="showSearch"
        style="margin-top: 14px"
        @change="triggerShowSearch"
      />
    </div>
    <!-- 修改 -->
    <div v-if="modelType == 7">
      <a-form :form="form"
        ><a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="架构名称">
          <a-input :placeholder="departName" v-decorator="['departName', validatorRules.departName]" />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>


<script>
import pick from 'lodash.pick'
import difference from 'lodash/difference'
import { postAction, getAction } from '@/api/manage'
// 穿梭框数据数组
const mockData = []
// 已选中的keys
const originTargetKeys = mockData.filter((item) => +item.key % 3 > 1).map((item) => item.key)
export default {
  data() {
    return {
      pagination1: {
        current: 1,
        pageSize: 10,
        //pageSizeOptions:['10','50','100'],
        showTotal: (total, range) => {
          //return range[0] + '-' + range[1] + '共' + total + '条'
          return '共' + total + '条'
        },
        showQuickJumper: false,
        showSizeChanger: false,
      },

      
      modelType: 0,
      title: '操作',
      visible: false,
      confirmLoading: false,
      disableSubmit: false,
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },

      validatorRules: {
        departName: {
          rules: [
            {
              required: true,
              message: '请输入架构名称!',
            },
            {
              validator: this.validateUsername,
            },
          ],
        }
      },

      /**穿梭框 */
      mockData: [],
      targetKeys: [],
      disabled: false,
      showSearch: false,
      leftColumns: [],
      rightColumns: [],
      /**穿梭框 */
      departName: '0',
      userinfo: [],
      url: {
        addSonGroup: '/sysdepart/sysDepart/addSonGroup',
        userNotDeptPageList: '/sysdepart/sysDepart/userNotDeptPageList',
        bindUserAndDept: '/sysdepart/sysDepart/bindUserAndDept',
        saveSameLevelGroup: '/sysdepart/sysDepart/saveSameLevelGroup',
        parkList:'/sysdepart/sysDepart/parkList',
        bindParkGroupAndPark:'/sysdepart/sysDepart/bindParkGroupAndPark',
        updateDeptName:'/sysdepart/sysDepart/updateDeptName'
      },
    }
  },

  methods: {

    // 查询要绑定的用户信息
    userNotDept() {
      let that = this
      getAction(this.url.userNotDeptPageList).then((res) => {
        if (res.success) {
          that.mockData.push(...res.result)
        } else {
          that.$message.warning(res.message)
        }
      })
    },

    // 查询要绑定的车场信息
    parkList() {
      let that = this
      let deptId = window.localStorage.getItem('deptId');
      getAction(this.url.parkList+'?id='+deptId).then((res) => {
        if (res.success) {
          let result = res.result;
          result.forEach(item =>{
            const param = Object.assign({}, {});
            param.key = item.id
            param.title = item.parkName
            that.mockData.push(param)
          })
        } else {
          that.$message.warning(res.message)
        }
      })
    },

    onChange(nextTargetKeys) {
      this.targetKeys = nextTargetKeys
    },
    onChange1(pagination) {
      this.pagination1.current = pagination.current
      this.pagination1.pageSize = pagination.pageSize
    },

    triggerDisable(disabled) {
      this.disabled = disabled
    },

    triggerShowSearch(showSearch) {
      this.showSearch = showSearch
    },
    getRowSelection({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: (item) => ({ props: { disabled: disabled || item.disabled } }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows.filter((item) => !item.disabled).map(({ key }) => key)
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys)
          itemSelectAll(diffKeys, selected)
        },
        onSelect({ key }, selected) {
          itemSelect(key, selected)
        },
        selectedRowKeys: selectedKeys,
      }
    },
    handleCancel() {
      this.close()
    },
    add(depart) {
      let _self = this
      if (depart) {
        this.seen = false
      } else {
        this.seen = true
      }
      if (depart.type == 5 || depart.type == 6) {
        let action = {
          // 添加用户
          5: function () {
            _self.userNotDept()
            _self.leftColumns = [
              {
                dataIndex: 'title',
                title: '全选',
              },
            ]
            _self.rightColumns = [
              {
                dataIndex: 'title',
                title: '全选',
              },
            ]
          },
          6: function name() {
            _self.parkList()
            _self.leftColumns = [
              {
                dataIndex: 'title',
                title: '全选',
              },
            ]
            _self.rightColumns = [
              {
                dataIndex: 'title',
                title: '全选',
              },
            ]
          },
        }
        action[depart.type]()
      }
      if (depart.departName) {
        this.departName = depart.departName
      }
      this.modelType = depart.type
      this.edit(depart.parentId)
    },
    edit(record) {
      //   this.initParkInfoList()this.loadTreeData()
      this.form.resetFields()
      this.model = Object.assign({}, {})
      this.visible = true

      this.model.parentId = record != null ? record.toString() : null

      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
            this.model,
            'departName',
            'departNameEn',
            'departNameAbbr',
            'departOrder',
            'description',
            'orgType',
            'parkCode',
            'orgCode',
            'mobile',
            'fax',
            'address',
            'memo',
            'status',
            'delFlag'
          )
        )
      })
    },
    close() {
      this.resdata()
      this.$emit('close')
      this.disableSubmit = false
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(this.model, values)

          //时间格式化
          let type = this.modelType
          let path = ''
          // 类型为3添加子车场组
          if (type == 3) {
            path = this.url.addSonGroup
          } else if (type == 4) {
            // 添加同级车场组
            path = this.url.saveSameLevelGroup
          } else if (type == 5) {
            // 车场或车场组绑定用户
            formData.ids = this.targetKeys
            path = this.url.bindUserAndDept
          } else if (type == 6) {
            // 车场组绑定车场
            formData.ids = this.targetKeys
            path = this.url.bindParkGroupAndPark
          }else if (type == 7) {
            // 修改
            path = this.url.updateDeptName
          }

          postAction(path, formData)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
              that.resdata()
            })
        }
      })
    },
    resdata() {
      this.mockData = []
      this.targetKeys = []
    },
  },
}
</script>

<style>
</style>